import java.util.Scanner;

// @author: Alan Westbay
// @date: 6/5/2013
// SSE 661 Project 2
// This program reproduces a virtual campfire story, where one person starts the story, then each of the next people contribute a section.
// The user can create a new story or join a currently ongoing one from the list of available options.
public class CampfireStory {


	/* In the main method of CampfireStory, the presentation component of this top-level PAC agent is initiated frist,
	 *	with a call to printMenu(). The aSA variable is the abstraction component and is used to check for available stories.
	 *  The main method itself is the control component: taking user input and activating the appropriate sub-agents.
	 */
	public static void main(String[] args) {
		AvailableStoriesAgent aSA = new AvailableStoriesAgent();	//Abstraction Component.
		Scanner in = new Scanner(System.in);

		printMenu(aSA);	//Print instructions and open stories.
		while(true)	//Main program loop
		{
			if(in.hasNextInt())	//If a story number has been entered, create a new thread based on a JoinStoryAgent, then wait for that thread to terminate.
			{
				JoinStoryAgent jSA = new JoinStoryAgent(aSA.getStoryConnection(in.nextInt()));
				Thread jSAT = new Thread(jSA);
				jSAT.start();
				try {
					jSAT.join();
				}
				catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			else if(in.nextLine().charAt(0) == 'c')	//If authoring a story is desired, create a new CreateStoryAgent, and run it's control component.
			{
				CreateStoryAgent cSA = new CreateStoryAgent();
				cSA.authorStory();
			}
			else if(in.nextLine().charAt(0) == 'r')		//Refresh current running stories list, if requested.
			{
				System.out.println("\nChecking for open stories...\n");
				aSA.displayRunningStories();
			}
			else if(in.nextLine().charAt(0) == 'e')	//Exit, if requested.
			{
				System.out.println("\nSee you next time!\n");
				System.exit(0);
			} else {
				System.out.println("Invalid input.");
			}
		}




	}

	//Presentation component of the CampfireStory top-level PAC agent.
	//Prints a menu, along with the running stories.
	private static void printMenu(AvailableStoriesAgent aSA)
	{
		System.out.println("\nWelcome to Virtual Campfire Stories!\n");
		System.out.println("Checking for open stories...\n");
		aSA.displayRunningStories();
		System.out.println("To join an open story, type the number preceeding it's name.");
		System.out.println("To create a story, type 'c'.");
		System.out.println("To refresh the list of open stories, type 'r'.");
		System.out.println("To exit, type 'e'.");
	}

}
